﻿#include "iocardmanager.h"
#include "iocard/D122.h"
#include <QDebug>
#include <QTime>
#include <QCoreApplication>

void IoCardManager::Sleep(int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
	m_bSetOn = false;
}

IoCardManager::IoCardManager(QObject *parent) : QObject(parent)
{

}

bool IoCardManager::Init()
{
    bool bRet = false;
    U16 existcards = 0;
    I16 ret = _d122_open(&existcards);
    if (ret == 0)
    {
        if (existcards == 0)
        {
            // MessageBox.Show("No any DIO Card !!!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            bRet = false;
        }
        else
        {
            ret = _d122_get_switch_card_num(0, &m_CardNo);
            bRet = ret == 0;
            if(ret == 0)
                qDebug()<<"m_CardNo:"<<m_CardNo;
        }
    }
    return bRet;
}

bool IoCardManager::SetLightOn(uint8_t index)
{
	if (Init() != 0)
		return false;
	_d122_write_port(m_CardNo, 4, 1 << index);
	Sleep(1);
	_d122_write_port(m_CardNo, 4 + index, 0);

    return true;
}

void IoCardManager::CloseLight()
{
	m_bSetOn = false;
	_d122_write_port(m_CardNo, 4, 0);
}

bool IoCardManager::SetLightAlwaysOn(uint8_t index)
{
	m_bSetOn = true;
	while (m_bSetOn)
	{
		if (Init() != 0)
			return false;
		_d122_write_port(m_CardNo, 4, 1 << index);
		Sleep(1);
		_d122_write_port(m_CardNo, 4, 0);
		Sleep(200);
	}

    return true;
}
